import { routes } from 'boot/routes';
import router from 'src/router';

export default {
  namespaced: true,
  state: {
    mobile: false,
    routes: [],
    auth: [],
    allAuth: [],
    routeTabs: [{ name: '首页', path: '/home', fullPath: '/home' }],
  },
  getters: {
    confirmAuth(s) {
      //这里做按钮权限控制，只有设置了按钮权限，并且用户又没有这个权限的才算是没有权限
      //allAuth
      return (v) => {
        //权限设置了
        if (s.allAuth.some((au) => au.action === v)) {
          //这里看用户有没有
          return s.auth.some((au) => au.action === v);
        }
        return true;
      };
    },
  },
  mutations: {
    updateMobile(s, v) {
      s.mobile = v;
    },
    updateRoutes(s, v) {
      s.routes = v;
    },
    updateAuth(s, v) {
      s.auth = v;
    },
    updateAllAuth(s, v) {
      s.allAuth = v;
    },
    addRouteTabs(s, v) {
      if (!s.routeTabs.find((r) => r.fullPath === v.fullPath)) {
        s.routeTabs.push(v);
        if (s.routeTabs.length === 11) {
          s.routeTabs.splice(s.routeTabs.indexOf(s.routeTabs[1]), 1);
        }
      }
    },
    updateRouteTabs(s, v) {
      if (!s.routeTabs.find((r) => r.fullPath === v.fullPath)) {
        const ind = s.routeTabs.findIndex((r) => r.name === v.name);
        if (ind !== -1) {
          s.routeTabs.splice(ind, 1);
          this.$router.replace(v.fullPath);
        }
      }
    },

    removeRouteTabs(s, p) {
      s.routeTabs.splice(s.routeTabs.findIndex((r) => r.fullPath === p), 1);
    },
    clear(s) {
      s.routes = [];
    },
  },
  actions: {
    dynamicRoutes({ commit }) {
      return new Promise((resolve) => {
        //菜单转换component动态import
        const imTr = (arr, menuList) => {
          arr.forEach((v) => {
            menuList.push({
              ...v,
              children: [],
            });
            if (v.children && v.children.length > 0) {
              imTr(v.children, menuList);
            }
          });
        };
        //这里换一个思路，把菜单拉平，这样就解决了布局的问题；
        const menuList = [];
        imTr(routes, menuList);
        router.addRoute(
          {
            path: '/',
            name: '功能列表',
            component: () => import('layouts/phone.vue'),
            children: menuList,
          },
        );
        commit('updateRoutes', routes);

        resolve();
      });
    },
  },
};
